import { createRouter, createWebHistory } from 'vue-router'
//导入组件
import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import Index from '@/views/edu/index/index.vue'
import { permissionStoreService } from '@/stores/permission.js'
import AllDescription from '@/views/edu/AllDescription/AllDescription.vue'
import NotFoundVue from '@/views/404.vue' // 引入404页面组件
import PasswordGetBackView from '@/views/getback/PasswordGetBackView.vue'

//定义路由关系
const routes = [
  {
    path: '',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'index',
    component: Index
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/allDescription/:taskId', // 添加这行，定义带参数的路由路径，:taskId是动态参数
    name: 'allDescription',
    component: AllDescription
  },
  // 404 页面捕获路由配置
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFoundVue // 使用404页面组件
  },
  {
    path: '/getBackPassword',
    name: { title: '忘记密码' },
    component: PasswordGetBackView
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: routes
})

export const setRoutes = () => {
  const permissionService = permissionStoreService()
  const permission = permissionService.permission
  const root = {
    path: '/layout',
    name: 'layout',
    component: Layout,
    children: []
  }
  if (permission && permission.length > 0) {
    for (const item of permission) {
      if (item.children?.length) {
        for (const c of item.children) {
          const router = {
            path: c.path,
            name: c.name,
            component: () => import('../views' + c.path + '.vue'),
            meta: { title: c.comment || c.name }
          }
          root.children.push(router)
        }
      } else {
        const route = {
          path: item.path,
          name: item.name,
          component: () => import('../views' + item.path + '.vue'),
          meta: { title: item.comment || item.name }
        }
        root.children.push(route)
      }
    }
  }
  router.addRoute(root)
}

router.beforeEach((to, from, next) => {
  const permissionStore = permissionStoreService()
  if (to.path === '/login') {
    next()
  } else {
    if (!permissionStore.permission) {
      next('/index')
    } else {
      next()
    }
  }
})

export default router
